<template>
  <div class="login-container">
    <div class="login-form-wrapper">
      <div class="login-header">
        <div class="login-logo">
          <el-icon class="logo-icon"><component is="i-airplane" /></el-icon>
        </div>
        <h2 class="login-title">无人机管理系统</h2>
        <p class="login-subtitle">请输入您的账号和密码</p>
      </div>
      
      <el-form
        :model="loginForm"
        :rules="loginRules"
        ref="loginFormRef"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="i-user"
            :prefix-icon-style="{ color: '#909399' }"
            clearable
            size="large"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="i-lock"
            :prefix-icon-style="{ color: '#909399' }"
            show-password
            size="large"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            @click="handleLogin"
            :loading="isLoading"
            class="login-btn"
            size="large"
            round
          >
            {{ isLoading ? '登录中...' : '登 录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import service from '@/utils/request'

export default {
  name: 'Login',
  setup() {
    const router = useRouter()
    const loginFormRef = ref(null)
    const isLoading = ref(false)
    
    const loginForm = reactive({
      username: 'admin',
      password: 'admin123'
    })
    
    const loginRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ]
    }
    
    const handleLogin = async () => {
      // 表单验证
      loginFormRef.value.validate(async (valid) => {
        if (valid) {
          isLoading.value = true
          try {
            // 使用URLSearchParams正确格式化表单数据（OAuth2PasswordRequestForm需要）
            const params = new URLSearchParams()
            params.append('username', loginForm.username)
            params.append('password', loginForm.password)
            
            // 使用配置好的service实例，确保请求拦截器正常工作
            const response = await service.post('/auth/login', params)
            
            // 正确处理后端ResponseModel结构
            const token = response.data?.access_token || response.data?.data?.access_token
            localStorage.setItem('token', token)
            
            ElMessage.success('登录成功')
            router.push({ name: 'Dashboard' })
          } catch (error) {
            console.error('登录失败:', error)
            // 处理不同的错误情况
            if (error.response) {
              switch (error.response.status) {
                case 401:
                  ElMessage.error('用户名或密码错误')
                  break
                case 403:
                  ElMessage.error('账号被禁用，请联系管理员')
                  break
                default:
                  ElMessage.error('登录失败，请稍后重试')
              }
            } else if (error.request) {
              // 如果后端服务不可用，使用模拟数据
              console.log('后端服务不可用，使用模拟数据登录')
              const mockToken = 'mock_token_' + Date.now()
              const mockUser = {
                id: 1,
                username: loginForm.username,
                full_name: '测试管理员',
                email: 'admin@example.com',
                role: 'admin'
              }
              localStorage.setItem('token', mockToken)
              localStorage.setItem('userInfo', JSON.stringify(mockUser))
              ElMessage.success('模拟登录成功（后端服务不可用）')
              router.push({ name: 'Dashboard' })
            } else {
              ElMessage.error('请求错误，请检查网络')
            }
          } finally {
            isLoading.value = false
          }
        }
      })
    }
    
    return {
      loginFormRef,
      isLoading,
      loginForm,
      loginRules,
      handleLogin
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-form-wrapper {
  width: 400px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.login-header {
  text-align: center;
  padding: 40px 40px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}

.login-logo {
  width: 60px;
  height: 60px;
  margin-bottom: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
}

.logo-icon {
  color: white;
  font-size: 30px;
}

.login-title {
  margin: 0 0 10px;
  font-size: 24px;
  font-weight: 500;
}

.login-subtitle {
  margin: 0;
  font-size: 14px;
  opacity: 0.9;
}

.login-form {
  padding: 40px;
}

.login-btn {
  width: 100%;
  padding: 12px;
  font-size: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.login-btn:hover {
  opacity: 0.9;
}
</style>